package com.ksd.quartz.task;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksd.common.config.PlayControlConfig;
import com.ksd.common.utils.DateUtils;
import com.ksd.common.utils.StringUtils;
import com.ksd.quartz.http.DRMHttpClient;
import com.ksd.quartz.http.NIOFileDownloader;
import com.ksd.quartz.task.beans.SynchApkRequest;
import com.ksd.quartz.task.beans.SynchJarResponse;
import com.ksd.quartz.task.beans.SynchVueResponse;
import com.ksd.quartz.util.FileUtil;
import com.ksd.quartz.util.SystemTool;
import com.ksd.quartz.util.TaskConstans;
import com.ksd.system.domain.SysApkVersion;
import com.ksd.system.domain.SysBoard;
import com.ksd.system.domain.SysContentSynch;
import com.ksd.system.service.ISysApkVersionService;
import com.ksd.system.service.ISysBoardService;
import com.ksd.system.service.ISysContentSynchService;
import com.ksd.system.service.ISysOperLogService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 每隔1小时向云服务器系统查询是否有待升级的机顶盒版本,如果有的话,需要将待升级apk下载同步到服务器上
 */
@Component("synchVueVersionTask")
public class SynchVueVersionTask {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(SynchVueVersionTask.class);

    @Autowired
    private ISysApkVersionService sysApkVersionService;
    @Autowired
    private ISysContentSynchService sysContentSynchService;
    @Autowired
    private ISysOperLogService sysOperLogService;


    public void getUiVersion()
    {
        SysContentSynch synchServiceData = sysContentSynchService.selectSysContentSynchById(SysContentSynch.cloudSynchFlag);
        //检查同步待升级的终端APK版本
        SysApkVersion sysApkVersion = new SysApkVersion();
        SynchApkRequest synchApkRequest = new SynchApkRequest();
        synchApkRequest.setOperatorKey(synchServiceData.getValue1());

        String requestGson = JSONObject.toJSONString(synchApkRequest);

        String url = synchServiceData.getValue2()+TaskConstans.synchVueVersionUrl;
        logger.info("[system-synchUI] SynchUiVersionTask Interface url :" + url);
        logger.info("[system-synchUI] SynchUiVersionTask Interface Request :" + requestGson);

        SysContentSynch synchVueOld = sysContentSynchService.selectSysContentSynchById(SysContentSynch.synch_ui_id);
        String response = DRMHttpClient.udrmHttpDoPost(url, requestGson);
        ObjectMapper mapperPage = new ObjectMapper();
        try {
            logger.info("response:"+response.toString());
            SynchVueResponse synchVueResponse = mapperPage.readValue(response, SynchVueResponse.class);
            logger.info("[system-synchUI] SynchUiVersionTask Interface response :" + synchVueResponse.toString());
            if (StringUtils.isNotNull(synchVueResponse)) {
                Integer status = synchVueResponse.getStatus();
                if (status == -1){
                    logger.info(synchVueResponse.getMessage());
                    sysOperLogService.insertOperlogApiError("后台系统前端页面同步接口响应状态失败:"+status);
                    return;
                }else{
                    //获取最新jar,将机顶盒jar包同步到本地
                    String apkPath = synchVueResponse.getVuePath();//该文件地址需要能够通过服务器直接访问到,即在云服务器上已部署在nginx指定目录下
                    String apkName = synchVueResponse.getVueName();
                    String apkVersion = synchVueResponse.getVueVersion();

                    if (StringUtils.isNotEmpty(apkVersion)) {
                        sysApkVersion.setVersion(apkVersion);
                    }
                    sysApkVersion.setType(3);
                    List<SysApkVersion> sysApkVersions = sysApkVersionService.selectSysApkVersionList(sysApkVersion);
                    String dataPath = File.separator+"playcontrol_ui_version"+File.separator+ DateUtils.dateTimeNow();
                    String downPath = PlayControlConfig.getNginxRootPath()+ dataPath+File.separator+apkName;
                    String mappedPath = PlayControlConfig.getMappingPath()+ dataPath+File.separator+apkName;
                    System.out.println("前端页面版本更新下载到服务器地址:"+downPath);
                    if (sysApkVersions.size() > 0) {
                        sysApkVersion = sysApkVersions.get(0);
                        if (!sysApkVersion.getCloudPath().equals(apkPath)){
                            logger.info("后台管理系统升级最新版本:"+apkVersion+"更新下载,将版本更新到服务地址:"+downPath);
                            sysOperLogService.insertOperlogApiSuccess("后台管理系统升级最新版本:"+apkVersion+"更新下载,将版本更新到服务地址:"+downPath);
                            //将该待升级的机顶盒apk下载下来,同时需要下载到指定目录下,即该系统服务器的nginx指定目录下
                           try {
                               boolean flag = NIOFileDownloader.downloadFile(apkPath, downPath);
                               if (flag){
                                   logger.info("前端升级文件下载成功,"+downPath);
                                   logger.info("版本更新映射到服务器的地址:"+mappedPath);
                                   sysOperLogService.insertOperlogApiSuccess("前端升级文件下载成功,"+downPath+" ,版本更新映射到服务器的地址:"+mappedPath);
                                   //同步升级信息

                                   sysApkVersion.setUrl(mappedPath);
                                   sysApkVersion.setCloudPath(apkPath);

                                   sysApkVersionService.updateSysApkVersion(sysApkVersion);
                               }else{
                                   logger.error("前端升级文件下载失败,"+downPath);
                                   sysOperLogService.insertOperlogApiError("前端升级文件下载失败,"+downPath);
                                   return;
                               }
                            } catch (IOException e) {
                                logger.error("前端升级文件下载失败: " + e.getMessage()+" ,待下载的前端版本地址:"+apkPath);
                               sysOperLogService.insertOperlogApiError("前端升级文件下载失败: " + e.getMessage()+" ,待下载的前端版本地址:"+apkPath);
                                return;
                            }
                        }else{
                            logger.info("前端升级版本:"+apkVersion+"已与云服务版本同步,无需下载更新");
                            sysOperLogService.insertOperlogApiSuccess("前端升级版本:"+apkVersion+"已与云服务版本同步,无需下载更新");
                            return;
                        }
                    }else {
                        logger.info("前端升级版本:"+apkVersion+",第一次同步,将版本更新到服务地址:"+downPath);
                        sysOperLogService.insertOperlogApiSuccess("前端升级版本:"+apkVersion+",第一次同步,将版本更新到服务地址:"+downPath);
                        try {
                            boolean flag = NIOFileDownloader.downloadFile(apkPath, downPath);
                            if (flag){
                                logger.info("前端升级文件下载成功:"+downPath);
                                logger.info("版本更新映射到服务器的地址:"+mappedPath);
                                sysOperLogService.insertOperlogApiSuccess("前端升级文件下载成功:"+downPath+" ,版本更新映射到服务器的地址:"+mappedPath);
                                //同步升级信息

                                sysApkVersion.setVersion(apkVersion);
                                sysApkVersion.setCloudPath(apkPath);
                                sysApkVersion.setUrl(mappedPath);
                                sysApkVersion.setType(3);

                                sysApkVersionService.insertSysApkVersion(sysApkVersion);
                            }else{
                                logger.error("前端升级文件下载失败,"+downPath);
                                sysOperLogService.insertOperlogApiError("前端升级文件下载失败,"+downPath);
                                return;
                            }
                        } catch (IOException e) {
                            logger.error("前端升级文件下载失败: " + e.getMessage()+" ,待下载的前端版本地址:"+apkPath);
                            sysOperLogService.insertOperlogApiError("前端升级文件下载失败: " + e.getMessage()+" ,待下载的前端版本地址:"+apkPath);
                            return;
                        }
                    }

                    //判断当前版本是否与系统同步版本一致,如果不一致,将原版本修改名字做备份,将当前版本复制到服务器指定位置下
                    //kill进程
                    String uiVersion = synchVueOld.getValue1();
                    if (StringUtils.isNotEmpty(uiVersion) && !uiVersion.equals(sysApkVersion.getVersion())) {

                        logger.info("实际服务器部署的前端版本并不一致,需要立即升级前端vue包.当前部署版本:"+uiVersion+" ,当前待升级版本:"+sysApkVersion.getVersion());
                        sysOperLogService.insertOperlogApiSuccess("实际服务器部署的前端版本并不一致,需要立即升级前端vue包.当前部署版本:"+uiVersion+" ,当前待升级版本:"+sysApkVersion.getVersion());
                        //解析服务器映射地址,改成服务器本地地址
                        logger.info("待升级的前端vue包在服务器的本地路径地址:"+downPath);
                        sysOperLogService.insertOperlogApiSuccess("待升级的前端vue包在服务器的本地路径地址:"+downPath);
                        //运行xshell脚本,进行系统升级
                        String xshellPath = PlayControlConfig.getXshellPath();
                        String sourcePath = xshellPath+"systemUpgrade_vue_template.sh";;
                        String newFilePath = xshellPath+"systemUpgrade_vue_new.sh";;
                        logger.info("脚本模本文件地址:"+sourcePath);
                        logger.info("升级脚本文件地址:"+newFilePath);
                        sysOperLogService.insertOperlogApiSuccess("脚本模本文件地址:"+sourcePath+",升级脚本文件地址:"+newFilePath);
                        FileUtil.readToWriteVue(sourcePath, newFilePath,downPath);
                        //重新修改待制定shell文件后
                        String os = System.getProperty("os.name").toLowerCase();
                        String cmd = "";
                        Object exec = null;
                        if (os.contains("win")) {
                            logger.info("部署在本地Windows版本系统暂时不支持升级");
                            sysOperLogService.insertOperlogApiSuccess("部署在本地Windows版本系统暂时不支持升级");
                        } else {
                            cmd = xshellPath+"systemUpgrade_vue_new.sh";   //Linux版本升級，使用脚本进行重启
                            //保证脚本执行权限
                            logger.info("系统升级执行复制生成的脚本"+cmd);
                            exec = SystemTool.execFile("linux", cmd);
                            logger.info("系统前端正在升级，请稍后");
                            if (StringUtils.isNotNull(synchVueOld)) {
                                synchVueOld.setValue1(sysApkVersion.getVersion());
                                sysContentSynchService.updateSysContentSynch(synchVueOld);
                            }
                        }
                    }else{
                        logger.info("实际服务器部署的前端版本一致,暂时不需要更新前端vue包版本."+uiVersion);
                        sysOperLogService.insertOperlogApiSuccess("实际服务器部署的前端版本一致,暂时不需要更新前端vue包版本."+uiVersion);
                    }
                }
            }else {
                sysOperLogService.insertOperlogApiError("后台系统前端页面同步接口响应数据为空.");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        logger.info("系统前端页面升级成功====================================end");
    }

}
